# encoding:utf-8
import datetime
import os.path
import smtplib
from email.header import Header as _Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

from jinja2 import FileSystemLoader, Environment
from logzero import logger

import config

SMTP_SERVER = config.SMTP_SERVER
FROM_ADDR = config.FROM_ADDR
PASSWORD = config.PASSWORD
TO_ADDRS = config.TO_ADDRS
PORT = config.port


def Header(name):
    return _Header(name, 'utf-8').encode()


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name), addr))


def gen_msg(content, subject, attachments, nick_from=None):
    if nick_from is None:
        nick_from = FROM_ADDR
    msg = MIMEMultipart()
    msg['From'] = _format_addr('{} <{}>'.format(nick_from, FROM_ADDR))
    msg['To'] = ','.join(TO_ADDRS)
    msg['Subject'] = Header(subject)
    msg.attach(MIMEText(content, 'html', 'utf-8'))

    for attchment in attachments:
        attach = MIMEText(open(attchment, 'rb').read(), 'base64', 'utf-8')
        attach['Content-Type'] = 'application/octet-stream'
        attach['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path.basename(attchment))
        msg.attach(attach)
    return msg


def get_email_html(**kwargs):
    current_dir = os.path.split(os.path.realpath(__file__))[0]
    env = Environment(loader=FileSystemLoader(os.path.join(current_dir, config.templates_dir)))
    template = env.get_template(config.template_html)
    template.stream(**kwargs).dump(
        os.path.join(current_dir, config.log_dir,
                     '%s.html' % (datetime.datetime.now().strftime("%Y-%m-%d %H %M %S"))))
    return template.render(**kwargs)


def sendmail(content, subject, attachments, nick_from=None):
    """
    可兼容SSL和TLS两种方式
    :param content: html内容
    :param subject: 邮件主题
    :param attachments: 附件地址列表
    :param nick_from: 发件人昵称
    :return:
    """
    logger.info(f'{nick_from}正在发送邮件')
    msg = gen_msg(content, subject, attachments, nick_from)
    try:
        server = smtplib.SMTP_SSL(SMTP_SERVER)
    except:
        server = smtplib.SMTP(host=SMTP_SERVER, port=PORT)
        server.starttls()
    server.login(FROM_ADDR, PASSWORD)
    server.sendmail(FROM_ADDR, TO_ADDRS, msg.as_string())
    server.quit()
    logger.info('发送完成')

if __name__ == '__main__':
    sendmail('<h1>我是内容</h1>', '我是主题', [], '发件机器人')
